export default class FRequest{
    constructor() { }

    config = {
        baseUrl:'',
        isJson:false,
        headers:{}
    }

    interceptor={
        request:(init)=>{
            return init;
        },
        response:{
            convert(res){
                return res;
            },
            next(res){
                return res;
            }
        }

    }


    getRealUrl(url){
        if(url.startsWith("/")){
            url = url.slice(1)
        }
        this.config.baseUrl = this.config.baseUrl ?? "";
        if(this.config.baseUrl.endsWith("/")){
            this.config.baseUrl = this.config.baseUrl.slice(0,-1)
        }
        return this.config.baseUrl + "/" + url;

    }


    post(url,params= {},headers={}){
        url = this.getRealUrl(url)
        if(this.config.isJson === true && !(params instanceof FormData)){
            params = JSON.stringify(params)
        }
        headers = {
            ...(this.config.headers ?? {}),
            ...headers,
        }

        return this.request(url,{
            method:"POST",
            headers:headers,
            body:params
        });

    }

    request(url,init){
        return new Promise((resolve,reject)=>{
            init = this.interceptor.request(init)
            if(init instanceof Promise){
                init.then((res)=>{
                    fetch(url,res).then(res=>this.interceptor.response.convert(res)).then(res=>{
                        this.interceptor.response.next(res);
                        resolve(res);
                    })
                })
            }else{
                fetch(url,init).then(res=>this.interceptor.response.convert(res)).then(res=>{
                    this.interceptor.response.next(res);
                    resolve(res);
                })
            }

        })
    }


    httpBuildQuery(params){
        let strArray = [];
        for(let key in params){
            strArray.push(key + '=' + params[key]);
        }
        // strArray => ['id=1','x=2']
        return strArray.join("&");
        // id=1&x=2


        // {
        //  id:1,
        //  x:2
        // }
        // id=1&x=2
    }

    get(url,params= {},headers={}){
        url = this.getRealUrl(url);
        let symbol = "?";
        if(url.endsWith("?") || url.endsWith("&")){
            symbol = "";
        }else if(url.includes("?")){
            symbol = "&"
        }
        url = url + symbol+ this.httpBuildQuery(params)

        headers = {
            ...(this.config.headers ?? {}),
            ...headers,
        }
        return this.request(url,{
            method:"GET",
            headers:headers,
        });
    }

}